from greader2kindle import GReaderConnection
from greader2kindle import FeedBuilder
import os
import sys
import getopt
from greader2kindle.docgenerator import DocGenerator
from greader2kindle.mail import mail

markRead = True
sendMail = True
deleteOutput = True

def usage():
    print "Usage:"
    print "\tgreader2kindle <g_username> <g_password> <tmpdir> <kindle-email>\n"
    sys.exit()

def main():
    # parse command line options
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
    except getopt.error, msg:
        print msg
        print "for help use --help"
        sys.exit(2)
    # print usage if demanded
    for o, _ in opts:
        if o in ("-h", "--help"):
            usage()
    # generate
    if len(args) != 4:
        usage() 
    (username, password, outdir, email) = args
    greader = GReaderConnection(username, password)
    greader.authenticate()
    builder = FeedBuilder(greader)
    feedCollections = builder.generateFeeds(markRead)
    if feedCollections == []:
        print "no collection for today..."
        quit()
    if not os.path.exists(outdir):
        print "create output directory"
        os.mkdir(outdir)
    docGen = DocGenerator(outdir, feedCollections)
    docGen.generate()
    if sendMail:
        mail(username, password, email, docGen.name, "enjoy", docGen.fname)
    if deleteOutput:
        print "cleanup ..."
        os.unlink(docGen.fname)
        
if __name__ == "__main__":
    main()